//
//  UIDatePickerViewController.swift
//  Example
//
//  Created by T AO on 2022/2/16.
//

import UIKit
import RxSwift
import RxCocoa

private let screenW = UIScreen.main.bounds.width
private let screenH = UIScreen.main.bounds.height

class UIDatePickerViewController: BaseViewController {
    
    private var datePicker: UIDatePicker!
    
    private var label: UILabel!
    
    private var startButton: UIButton!
    
    private var leftTime = BehaviorRelay(value: TimeInterval(180))
    
    /// 当前倒计时是否结束
    private let countDownStopped =  BehaviorRelay(value: true)
    
    private lazy var dateFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy年MM月dd日 HH:mm"
        return formatter
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        makeUI()
        
        datePickerRx()
        countDown()
    }
    
    private func makeUI() {
        datePicker = UIDatePicker(frame: CGRect(x: 0, y: screenH - 400, width: screenW, height: 400))
        datePicker.datePickerMode = .countDownTimer
        view.addSubview(datePicker)
        
        label = UILabel(frame: CGRect(x: 0, y: screenH - 400 - 100, width: screenW, height: 50))
        view.addSubview(label)
        
        startButton = UIButton(type: .custom)
        startButton.frame = CGRect(x: 0, y: screenH - 400 - 100 - 100, width: screenW, height: 50)
        startButton.setTitleColor(.red, for: .normal)
        startButton.setTitleColor(.gray, for: .disabled)
        view.addSubview(startButton)
    }

}

// MARK: - UIDatePicker

extension UIDatePickerViewController {
    private func datePickerRx() {
        datePicker.rx.date
            .map { [weak self] in
                guard let self = self else { return "" }
                let dateStr = self.dateFormatter.string(from: $0)
                return "当前选择的时间: \(dateStr)"
            }
            .bind(to: label.rx.text)
            .disposed(by: disposeBag)
    }
    
    /// 写一个通过时间选择器来实现倒计时
    private func countDown() {
        DispatchQueue.main.async {
            self.datePicker.rx.countDownDuration <-> self.leftTime
        }
        
        // 绑定按钮内容
        Observable.combineLatest(leftTime.asObservable(), countDownStopped.asObservable()) { leftTimeValue, countDownValue in
            return countDownValue ? "开始" : "倒计时开始，还有 \(Int(leftTimeValue)) 秒..."
        }
        .bind(to: startButton.rx.title())
        .disposed(by: disposeBag)
        
        // 绑定 button 和 datePicker 状态（在倒计时过程中，按钮和时间选择组件不可用）
        countDownStopped.asDriver().drive(startButton.rx.isEnabled).disposed(by: disposeBag)
        countDownStopped.asDriver().drive(datePicker.rx.isEnabled).disposed(by: disposeBag)
        
        startButton.rx.tap
            .bind { [weak self] in
                self?.start()
            }
            .disposed(by: disposeBag)
    }
    
    private func start() {
        // 开始倒计时
        countDownStopped.accept(false)
        
        Observable<Int>.interval(RxTimeInterval.seconds(1), scheduler: MainScheduler.instance)
            .take(until: countDownStopped.asObservable().filter { $0 }) // 倒计时结束时停止计时器
            .subscribe{ event in
                // 每次剩余时间 -1
                let time = self.leftTime.value - 1
                self.leftTime.accept(time)
                
                // 如果剩余时间 <= 0
                if self.leftTime.value <= 0 {
                    print("倒计时结束!")
                    self.countDownStopped.accept(true)
                    self.leftTime.accept(TimeInterval(180))
                }
            }
            .disposed(by: disposeBag)
    }
}
